package com.hctg.forced2sleep.utils;

import android.Manifest;
import android.app.Activity;
import android.app.Application;
import android.app.WallpaperInfo;
import android.app.WallpaperManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.service.wallpaper.WallpaperService;
import android.text.TextUtils;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RawRes;
import androidx.annotation.RequiresPermission;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;

import com.actor.myandroidframework.utils.ConfigUtils;
import com.actor.myandroidframework.utils.LogUtils;
import com.actor.myandroidframework.utils.MMKVUtils;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.hctg.forced2sleep.R;
import com.hjq.permissions.XXPermissions;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * description: 墙纸工具类 <br />
 * {@link null 注意:} if要设置壁纸的话, 需要声明权限
 * <pre>
 *     &lt;uses-permission android:name="android.permission.SET_WALLPAPER" /&gt;
 * </pre>
 *
 *
 * @author : ldf
 * @date   : 2024/5/2 on 16
 * @version 1.0
 */
public class WallpaperUtils {

    //视频地址
    protected static final String VIDEO_PATH_FOR_WALLPAPER_UTILS = "VIDEO_PATH_FOR_WALLPAPER_UTILS";
    protected static final String IS_VIDEO_WALLPAPER = "IS_VIDEO_WALLPAPER";

    /**
     * 获取桌面壁纸 (高版本手机需要读取权限)
     * FLAG_LOCK  : 可获取当前锁屏壁纸
     * FLAG_SYSTEM: 可获取当前系统桌面壁纸
     */
    @RequiresPermission(value = Manifest.permission.READ_EXTERNAL_STORAGE)
    @Nullable
    public static Drawable getWallpaperDesktop(Context context) {
        WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
        return wallpaperManager.getDrawable(); // BitmapDrawable, 获取当前系统桌面壁纸
    }

    /**
     * 获取锁屏壁纸 (暂未实现)
     * FLAG_LOCK  : 可获取当前锁屏壁纸
     * FLAG_SYSTEM: 可获取当前系统桌面壁纸
     */
    @Nullable
    public static Drawable getWallpaperLockScreen(Context context) {
//        WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
//        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
//            int wallpaperId =  wallpaperManager.getWallpaperId(WallpaperManager.FLAG_LOCK);
//            ParcelFileDescriptor wallpaperFile = wallpaperManager.getWallpaperFile(WallpaperManager.FLAG_LOCK);
//        } else {
//            wallpaperManager.getWallpaperInfo().getWallpaperUri();
//        }
        return null;
    }

    /**
     * 是否允许设置墙纸
     * @deprecated TODO: 2024/6/24 一直返回的true,
     */
    public static boolean isSetWallpaperAllowed(@NonNull Context context) {
        WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {           //Android 7.0
            boolean isAllowed =  wallpaperManager.isSetWallpaperAllowed();
            LogUtils.errorFormat("isAllowed=%b", isAllowed);
            return isAllowed;           //一直返回true
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {    //Android 6.0
            boolean wallpaperSupported = wallpaperManager.isWallpaperSupported();
            LogUtils.errorFormat("wallpaperSupported=%b", wallpaperSupported);
            return wallpaperSupported;  //一直返回true
        } else {
            boolean granted = XXPermissions.isGranted(context, Manifest.permission.SET_WALLPAPER);
            LogUtils.errorFormat("granted=%b", granted);
            return granted;             //一直返回true
        }
    }

    //查询当前壁纸app的包名
    public static boolean isWallpaperServiceOpened(@NonNull Class<? extends WallpaperService> wallpaperService) {
        WallpaperInfo wallpaperInfo = WallpaperManager.getInstance(ConfigUtils.APPLICATION).getWallpaperInfo();
        if (wallpaperInfo == null) {    //调用自定义壁纸服务 设置图片壁纸前
            return false;
        } else {
            String serviceName = wallpaperInfo.getServiceName();
            return TextUtils.equals(wallpaperService.getName(), serviceName);
        }
    }

    /**
     * 设置壁纸, 需要权限: android.Manifest.permission.SET_WALLPAPER
     * @param resId R.drawable.xxx, R.mipmap.xxx, R.raw.xxx
     * @param which 设置到桌面or锁屏or两者, Api24(Android 7.0)及以上才有效, 例: WallpaperManager.FLAG_LOCK, FLAG_SYSTEM
     * @return 新设置壁纸的id, 失败会返回0, Android 7以下会返回1.
     */
    @RequiresPermission(value = Manifest.permission.SET_WALLPAPER)
    public static int setResource(Context context, @DrawableRes @RawRes int resId, int which) {
        WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                return wallpaperManager.setResource(resId, which);
            } else {
                wallpaperManager.setResource(resId);
                return 1;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 设置壁纸, 需要权限: android.Manifest.permission.SET_WALLPAPER
     * @param bitmap 图片
     * @param which 设置到桌面or锁屏or两者, Api24(Android 7.0)及以上才有效, 例: WallpaperManager.FLAG_LOCK, FLAG_SYSTEM
     * @return 新设置壁纸的id, 失败会返回0, Android 7以下会返回1.
     */
    @RequiresPermission(value = Manifest.permission.SET_WALLPAPER)
    public static int setBitmap(Context context, @NonNull Bitmap bitmap, int which) {
        if (bitmap == null) return 0;
        WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                return wallpaperManager.setBitmap(bitmap, null, true, which);
            } else {
                wallpaperManager.setBitmap(bitmap);
                return 1;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 设置图片壁纸到桌面/锁屏 (不需要申请设置壁纸的权限)
     * @param picturePath 本地图片路径
     * @param wallpaperService 壁纸服务
     */
    public static void setPictureWallPaper(Context context, @NonNull String picturePath, Class<? extends WallpaperService> wallpaperService) {
        if (!FileUtils.isFile(picturePath)) return;
        //要先清除一下, 否则第1次回设置失败(vivo x27, Android 10)
        boolean clear = WallpaperUtils.clear(context, WallpaperManager.FLAG_SYSTEM);
        MMKVUtils.putString(VIDEO_PATH_FOR_WALLPAPER_UTILS, picturePath);
        MMKVUtils.putBoolean(IS_VIDEO_WALLPAPER, false);
        Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
        intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, new ComponentName(context, wallpaperService));
        context.startActivity(intent);
    }

    /**
     * 设置视频壁纸到桌面/锁屏 (不需要申请设置壁纸的权限)
     * @param videoPath 本地视频路径
     * @param wallpaperService 壁纸服务
     */
    public static void setVideoWallPaper(Context context, @NonNull String videoPath, Class<? extends WallpaperService> wallpaperService) {
        if (!FileUtils.isFile(videoPath)) return;
        //要先清除一下, 否则第1次会设置失败(vivo x27, Android 10)
        boolean clear = WallpaperUtils.clear(context, WallpaperManager.FLAG_SYSTEM);
        MMKVUtils.putString(VIDEO_PATH_FOR_WALLPAPER_UTILS, videoPath);
        MMKVUtils.putBoolean(IS_VIDEO_WALLPAPER, true);
        Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
        intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, new ComponentName(context, wallpaperService));
        context.startActivity(intent);
    }

    /**
     * 获取视频路径 <br />
     * 当系统重启本app的时候, 会重启壁纸服务, 将上次设置的视频壁纸路径返回
     */
    @Nullable
    public static boolean getIsVideoWallpaper() {
        return MMKVUtils.getBoolean(IS_VIDEO_WALLPAPER, false);
    }

    /**
     * 获取视频路径 <br />
     * 当系统重启本app的时候, 会重启壁纸服务, 将上次设置的视频壁纸路径返回
     */
    @Nullable
    public static String getVideoPath() {
        return MMKVUtils.getString(VIDEO_PATH_FOR_WALLPAPER_UTILS);
    }

    /**
     * 清除当前设备的壁纸，恢复为默认壁纸, 需要权限: android.Manifest.permission.SET_WALLPAPER
     * @param which 清除桌面or锁屏or两者, Api24(Android 7.0)及以上才有效, 例: WallpaperManager.FLAG_LOCK, FLAG_SYSTEM
     * @return 是否清除成功
     */
    @RequiresPermission(value = Manifest.permission.SET_WALLPAPER)
    public static boolean clear(@NonNull Context context, int which) {
//        try {
//            context.clearWallpaper();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                wallpaperManager.clear(which);
            } else {
                wallpaperManager.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 调用系统, 打开系统 "选择&设置壁纸" 的选项
     * @param requestCode 请求码
     */
    public static boolean chooseWallpaper(@Nullable Activity activity, @Nullable Fragment fragment, int requestCode) {
        Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
        Intent chooser = Intent.createChooser(pickWallpaper, StringUtils.getString(R.string.choose_wallpaper));
        if (activity != null) {
            activity.startActivityForResult(chooser, requestCode);
            return true;
        } else if (fragment != null) {
            fragment.startActivityForResult(chooser, requestCode);
            return true;
        } else {
            return ActivityUtils.startActivity(chooser);
        }
    }

    /**
     * 调用系统, 打开系统的壁纸设置页面, 包括 '静态壁纸' & '动态壁纸'
     * @param requestCode 请求码
     */
    public static boolean chooseWallpaper2(@Nullable Activity activity, @Nullable Fragment fragment, int requestCode) {
        Intent chooser = new Intent();
        chooser.setAction(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER);
        if (activity != null) {
            activity.startActivityForResult(chooser, requestCode);
            return true;
        } else if (fragment != null) {
            fragment.startActivityForResult(chooser, requestCode);
            return true;
        } else {
            return ActivityUtils.startActivity(chooser);
        }
    }

    /**
     * 调用系统, 裁剪并设置壁纸
     * @param filePath 图片路径
     * @param requestCode 请求码
     */
    public static boolean setWallpaperAndCrop(@Nullable Activity activity, @Nullable Fragment fragment, @NonNull String filePath, int requestCode) {
        if (filePath == null) {
            LogUtils.error("filePath is null!!");
            return false;
        }
        Intent intent = new Intent(WallpaperManager.ACTION_CROP_AND_SET_WALLPAPER);
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        String mime = "image/*";
        intent.putExtra("SET_LOCKSCREEN_WALLPAPER", true);
        File file = new File(filePath);
        Application context = ConfigUtils.APPLICATION;
        Uri uri = FileProvider.getUriForFile(context, context.getPackageName() + ".utilcode.fileprovider", file);
        intent.setDataAndType(uri, mime);
        if (activity != null) {
            activity.startActivityForResult(intent, requestCode);
            return true;
        } else if (fragment != null) {
            fragment.startActivityForResult(intent, requestCode);
            return true;
        } else {
            return ActivityUtils.startActivity(intent);
        }
    }

    /**
     * 查询所有壁纸服务
     */
    public static void queryIntentServices() {
        PackageManager packageManager = ConfigUtils.APPLICATION.getPackageManager();
        Intent intent = new Intent(WallpaperService.SERVICE_INTERFACE);
        List<ResolveInfo> list = packageManager.queryIntentServices(intent, PackageManager.GET_META_DATA);
        for (ResolveInfo resolveInfo : list) {
            //com.hctg.forced2sleep.service.MyWallpaperService
            String serviceName =  resolveInfo.serviceInfo.name;
            LogUtils.error(GsonUtils.toJson(resolveInfo));

            //打开某个服务, 去设置壁纸
//            Intent intent1 = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
//            intent1.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, resolveInfo.getComponent());
//            startActivity(intent1);
        }
    }

    // TODO: 2024/10/7 ???
    public static String R() {
        ResolveInfo resolveInfo = ConfigUtils.APPLICATION.getPackageManager()
                .resolveActivity(new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER), 0);
        if (resolveInfo == null) return null;
        ActivityInfo activityInfo = resolveInfo.activityInfo;
        if (activityInfo == null) return null;
        return activityInfo.packageName;
    }

}
